package com.example.myapplication

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jsoup.Jsoup
import java.io.IOException

class BaiduImageLoader(
    private val onDataLoaded: (List<String>) -> Unit,
    private val onError: () -> Unit
) {

    fun loadImages() {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                // Fetch Baidu homepage to get a list of image URLs
                val document = Jsoup.connect("https://www.baidu.com").get()
                val imageElements = document.select("img")
                val imageUrls = imageElements.map { "http:"+it.attr("src") }
                    //.filter { it.endsWith(".jpg", true) || it.endsWith(".png", true) }

                onDataLoaded(imageUrls)
                Thread.sleep(5000)

                val imageUrls2 = imageElements.map { "http:"+it.attr("src") }
                .filter { it.endsWith(".jpg", true) || it.endsWith(".png", true) }
                onDataLoaded(imageUrls2)


            } catch (e: IOException) {
                e.printStackTrace()
                onError()
            }
        }
    }
}
